extends ../layout

block content
  - var img_src = card.avatar.source || '';
  - var img_area = card.avatar.area || [];

  .container
    .row
      .col-lg-12
        include ../includes/message
        h2
          i.fa.fa-smile-o
          |  设置头像 &nbsp;
          a.btn.btn-primary(href="/card/"+card.id)
            span.fa.fa-angle-left
            |  完 成
      .col-lg-12
        p
          | 上传自己喜欢的图片展示个性，或点击“完成”回到编辑页面&nbsp;
          //- i.fa.fa-arrow-circle-right
          span#info.text-danger
        hr
  .container
    .row
      .col-sm-6.col-xs-12.pull-left

        img.img-responsive.pull-right.img_placehoder#imgarea
        .clearfix
        br
      .col-sm-6.col-xs-12.pull-right
        .row
          .col-xs-12
            .col-sm-12.col-xs-12
              form#request_form(method="post", enctype="multipart/form-data")
                .col-xs-9.col-sm-6(style="padding-left: 0")
                  input.form-control.text-center(type="file", name="avatar", id="avatar", required)
                //- button.btn.btn-default#choose(type="submit") 选择图片
                button.btn.btn-default#upload(type="submit") 上 传
                //- | &nbsp;&nbsp;
                p.help-block
                  i.fa.fa-spinner.fa-lg.text-muted#spinner.hidden
                  span#info.text-danger
                  //- span#info.text-danger 上传失败，请重试！
                p.help-block
                  span 只支持上传 1M 以下大小 JPG，PNG 格式图像。
                  br
                  span.text-info 上传后，拖拽或调整大图中的虚线方格，下方的预览小图即为保存后的头像。
            .col-sm-12.col-xs-12
              form#save_avatar(method="post")
                input#x(type="hidden", name="x")
                input#y(type="hidden", name="y")
                input#w(type="hidden", name="w")
                input#h(type="hidden", name="h")
                input#tempimage(type="hidden", name="image")
                button.btn.btn-success.disabled#save(type="submit") 保 存 头 像
          .clearfix
          br

        .row
          .col-xs-12.col-sm-3
            .preview(style="width:120px;height:120px;overflow:hidden;margin-left: 15px").pull-left
              img#preview_img
              //- img#preview_img(src="http://lorempixel.com/140/140/city")
            .clearfix
            br

append styles
  link(rel='stylesheet', href="//cdn.staticfile.org/jquery-jcrop/0.9.12/css/jquery.Jcrop.min.css")

append scripts
  script(type="text/javascript", src="//cdn.staticfile.org/jquery-validate/1.12.0/jquery.validate.min.js")
  script(type="text/javascript", src="//cdn.staticfile.org/jquery-validate/1.12.0/additional-methods.min.js")
  script(type="text/javascript", src="/javascripts/validator_methods.js")
  script(type="text/javascript", src="//cdn.staticfile.org/jquery-jcrop/0.9.12/js/jquery.Jcrop.min.js")
  script(type="text/javascript", src="http://libs.useso.com/js/jquery.form/3.50/jquery.form.min.js")
  //- script(type="text/javascript", src="/components/bootbox/bootbox.js")
  script.

    var jcrop_api;
    var xsize = 120;
    var ysize = 120;
    var boundx;
    var boundy;

    function updatePreview(c) {
      if (parseInt(c.w) > 0) {
        var rx = xsize / c.w;
        var ry = ysize / c.h;

        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#w').val(c.w);
        $('#h').val(c.h);
        //- console.log(c);

        $('#preview_img').css({
          width: Math.round(rx * boundx) + 'px',
          height: Math.round(ry * boundy) + 'px',
          marginLeft: '-' + Math.round(rx * c.x) + 'px',
          marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
      }
    }

    function JcropSetup(avatar) {
      var src = '/uploads/images/' + avatar.source;
      if (jcrop_api) jcrop_api.destroy(); //tear down firstly
      //- if (jcrop_api) jcrop_api.release(); //tear down firstly
      $('#tempimage').val(src);
      $('#imgarea').replaceWith('<img class="img-responsive pull-right" id="imgarea" src="'+src+'">');
      //- $('.img_placehoder').parent().toggleClass('hidden');
      //- $('#uploaded_img').attr('src', src);
      $('#preview_img').attr('src', src).attr('style', '');
      $('#save').removeClass('disabled');
      var area = avatar.area;
      var selection = [area[0], area[1], area[0]+area[2], area[1]+area[3]];
      //- console.log(selection);
      var theImage = new Image();
      theImage.src = src;
      $(theImage).load(function() {
        var w = this.width;
        var h = this.height;
        //- var dimension = Math.min(w, h)*.9;
        //- var iniSelect = [
        //-   w*.5 - dimension*.5,
        //-   h*.5 - dimension*.5,
        //-   w*.5 + dimension*.5,
        //-   h*.5 + dimension*.5,
        //- ];
        //- iniSelect = avatar.area;
        //- console.log(iniSelect);
        $('#imgarea').Jcrop({
          onSelect: updatePreview,
          onChange: updatePreview,
          aspectRatio: 1,
          trueSize: [w, h],
          bgOpacity: .4
        }, function() {
          // Use the API to get the real image size
          var bounds = this.getBounds();
          boundx = bounds[0];
          boundy = bounds[1];
          jcrop_api=this;
          jcrop_api.setSelect(selection);
        });

      });
    }

    $(document).ready(function() {
      var button_save = $('#save');
      var request_form = $('#request_form'); // cache form jq handler
      var save_avatar = $('#save_avatar'); // cached form handler
      request_form.ajaxForm({
        //- url: '/upload',
        //- type: 'POST',
        success: function(res, status, xhr, _form) {
          if (!res.success) {
            console.log(res.data);
            $('#info').text(res.data.message);
          } else {
            console.log(res.data);
            JcropSetup(res.data.avatar);
          }
          $('#spinner').removeClass('fa-spin').addClass('hidden');
          request_form.resetForm();
        },
        error: function (res, status, error) {
          //- $('#spinner').removeClass('fa-spin').addClass('hidden');
          request_form.resetForm();
        }
      });

      $('#upload').click(function() {
        if ($('#avatar').val() && request_form.valid()) {
          console.log('spinning...');
          $('#spinner').addClass('fa-spin').removeClass('hidden');
        }
        //- return false;
      });

      $('#save').click(function() {
        $('#spinner').addClass('fa-spin').removeClass('hidden');
      });

      var jumpTo = window.location.href.replace('/avatar', '');
      //- console.log(jumpTo);
      save_avatar.ajaxForm({
        success: function(res, status, xhr, _form) {
          if (!res.success) {
            $('#info').text(res.data.message || '保存失败，请重新上传');
            //- button_save.addClass('disabled')
          } else {
            //- $('<span class="text-success">'+res.data.message+'</span>').insertAfter('#info');
            $('#info').text(res.data.message);
            button_save.addClass('disabled');
            window.setTimeout(function() { window.location.href = jumpTo; }, 800);
          }
          $('#spinner').removeClass('fa-spin').addClass('hidden');
        },
        error: function (res, status, error) {
          $('#info').text('网络错误，请重试');
          $('#spinner').removeClass('fa-spin').addClass('hidden');
        }
      });

      // 初始化
      //- var current_src = "!{img_src}".trim();
      var avatar = !{card.avatar};
      //- console.log(area);
      if (avatar.source) {
        JcropSetup(avatar);
      }
    });

  script.
    $("#request_form").validate({
      //- debug: true,
      errorClass: "text-warning",
      errorElement: "span",
      errorPlacement: function (error, element) {
        error.insertAfter('#spinner');
      },
      rules: {
        avatar: {
          required: true,
          extension: "jpe?g|png",
          accept: "image/*",
          filesize: 1*1024*1024
        }
      },
      messages: {
        avatar: {
          required: "请选择要上传的图片",
          extension: "请上传 JPG 或 PNG 格式图片",
          accept: "请上传 JPG 或 PNG 格式图片文件",
          filesize: "请上传小于 1M 的文件"
        }
      }
    });